package com.exam.filter;

import com.exam.domain.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",asyncSupported = true) // 拦截所有请求
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        HttpSession session = httpRequest.getSession(false);

        // 获取请求路径
        String uri = httpRequest.getRequestURI();
//        System.out.println("过滤器接收到请求路径："+uri);
        // 静态资源目录不拦截，判断是否是静态资源（例如 .css, .js, .jpg, .png 等）
        if (uri.contains("/static/")) {
            // 如果是静态资源，直接放行
            chain.doFilter(request, response);
            return;
        }

        // 启动异步支持，确保异步操作仅在需要时启动


        // 如果是登录页面或Servlet，不拦截
        if (uri.endsWith("/login.jsp") || (uri.startsWith("/user/login") && uri.endsWith("/user/login") && "POST".equals(httpRequest.getMethod()))) {
            System.out.println("放行..."+uri);
            if (httpRequest.isAsyncSupported()&&uri.endsWith("/user/login")) {
                System.out.println("支持异步...");
                // 启动异步操作
                request.startAsync();
            }
            chain.doFilter(request, response);
            return;
        }

        // 如果Session中没有用户信息，重定向到登录页面
        if (session == null || session.getAttribute("user") == null) {
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login.jsp");

        } else {
//            session.getAttribute("user")
            // 用户已登录，放行请求
            User user = (User)session.getAttribute("user");
            System.out.println("登录的是"+user.getUserType());
            if("student".equals(user.getUserType())){
                if(uri.startsWith("/teacher")){
                    httpResponse.sendRedirect(httpRequest.getContextPath() +"/login.jsp");
                    return;
                }
            }else{
                if(uri.startsWith("/student")){
                    System.out.println("权限不符合，重定向到登录页面");
                    httpResponse.sendRedirect(httpRequest.getContextPath() +"/login.jsp");
                    return;
                }
            }
            chain.doFilter(request, response);
        }
    }
}
